package com.sxjh.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxjh.entity.TrainBookedEntity;
import com.sxjh.entity.param.TrainParam;
import com.sxjh.mapper.TrainBookedMapper;
import com.sxjh.service.TrainBookedService;
import com.sxjh.uitl.PageUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Service
@RequiredArgsConstructor
public class TrainBookedImpl extends ServiceImpl<TrainBookedMapper, TrainBookedEntity> implements TrainBookedService {

    @Autowired
    private TrainBookedMapper trainBookedMapper;

    @Override
    public PageUtil<TrainBookedEntity> getTrainBooked(TrainParam param) {
        PageUtil<TrainBookedEntity> pageUtil = new PageUtil<>();
        QueryWrapper<TrainBookedEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("belongs_factory",param.getBelongsFactory());
        if(!StringUtils.isEmpty(param.getBatchNumber())) queryWrapper.eq("batch_number",param.getBatchNumber());
        if(!StringUtils.isEmpty(param.getCarNumber())) queryWrapper.eq("car_number",param.getCarNumber());
        if(!StringUtils.isEmpty(param.getEachDistrict())) queryWrapper.like("each_district",param.getEachDistrict());
        if(!StringUtils.isEmpty(param.getFactoryName())) queryWrapper.like("factory_name",param.getFactoryName());
        if(!StringUtils.isEmpty(param.getStartTime())) queryWrapper.ge("extract_date",param.getStartTime());
        if(!StringUtils.isEmpty(param.getEndTime())) queryWrapper.le("extract_date",param.getEndTime());
        pageUtil.setPageNum(param.getCurrPage());
        pageUtil.setPageSize(param.getPageSize());
        pageUtil.setMyList(trainBookedMapper.selectList(queryWrapper));
        TrainBookedEntity total = new TrainBookedEntity();
        total.setBatchNumber("总计：");
        BigDecimal totalNetWeight = new BigDecimal(0.00);
        for (TrainBookedEntity mList : pageUtil.getMyList()) {
            total.setDeterminationWater(total.getDeterminationWater() + mList.getDeterminationWater());
            total.setAshContent(total.getAshContent() + mList.getAshContent());
            total.setVolatileMatter(total.getVolatileMatter() + mList.getVolatileMatter());
            total.setSulfurContent(total.getSulfurContent() + mList.getSulfurContent());
            total.setM40(total.getM40() + mList.getM40());
            total.setM10(total.getM10() + mList.getM10());
            totalNetWeight = totalNetWeight.add(mList.getNetWeight());
        }
        total.setNetWeight(totalNetWeight.setScale(2, BigDecimal.ROUND_HALF_UP));
        total.setDeterminationWater(new BigDecimal(total.getDeterminationWater() / pageUtil.getMyList().size()).setScale(2,BigDecimal.ROUND_HALF_UP).floatValue());
        total.setAshContent(new BigDecimal(total.getAshContent() / pageUtil.getMyList().size()).setScale(2,BigDecimal.ROUND_HALF_UP).floatValue());
        total.setVolatileMatter(new BigDecimal(total.getVolatileMatter() / pageUtil.getMyList().size()).setScale(2,BigDecimal.ROUND_HALF_UP).floatValue());
        total.setSulfurContent(new BigDecimal(total.getSulfurContent() / pageUtil.getMyList().size()).setScale(2,BigDecimal.ROUND_HALF_UP).floatValue());
        total.setM40(new BigDecimal(total.getM40() / pageUtil.getMyList().size()).setScale(2,BigDecimal.ROUND_HALF_UP).floatValue());
        total.setM10(new BigDecimal(total.getM10() / pageUtil.getMyList().size()).setScale(2,BigDecimal.ROUND_HALF_UP).floatValue());
        pageUtil.getData().add(total);
        return pageUtil;
    }

    @Override
    public Map<String, Object> importExcel(MultipartFile file,List<String[]> strArr,String belongsFactory) {
        Map<String,Object> result = new HashMap<>();
        int index = 0;
        int succeedCount = 0;
        int errCount = 0;
        String errMsg = "";
//        QueryWrapper<TrainBookedEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("each_district","娄底");
//        System.out.println(trainBookedMapper.selectList(queryWrapper));
        for (String[] strings : strArr) {
            try {
                //由于使用poi插件导入 日期会被转换为数字 单独处理
                Calendar calendar = new GregorianCalendar(1900,0,-1);
                Date d = calendar.getTime();
                Date dd = DateUtils.addDays(d,Integer.valueOf(strings[19]));
                LocalDateTime localDateTime = dd.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();

                TrainBookedEntity trainBookedEntity = new TrainBookedEntity(
                        strings[0],strings[1],strings[2],new BigDecimal(strings[3]),new BigDecimal(strings[4]),new BigDecimal(strings[5]),
                        Float.parseFloat(strings[6]),Float.parseFloat(strings[7]),Float.parseFloat(strings[8]),Float.parseFloat(strings[9]),
                        Float.parseFloat(strings[10]),Float.parseFloat(strings[11]),Float.parseFloat(strings[12]),Float.parseFloat(strings[13]),
                        strings[14],strings[15],strings[16],strings[17],strings[18], localDateTime,strings[20],belongsFactory
                );
                trainBookedMapper.insert(trainBookedEntity);
                succeedCount++;
            }catch (Exception e){
                e.printStackTrace();
                errMsg+= "第"+index+"行，导入失败！请检查数据完整性！";
                errCount++;
                continue;
            }finally {
                index++;
            }
        }
        result.put("succeedCount",succeedCount);
        result.put("errCount",errCount);
        result.put("errMsg",errMsg);
        return result;
    }

    @Override
    public TrainBookedEntity getTrainBookedById(TrainParam param) {
        return trainBookedMapper.selectById(param.getId());
    }

    @Override
    public String modifyTrainBooked(TrainBookedEntity param) {
        if(trainBookedMapper.updateById(param) == 1){
            return "修改成功！";
        }
        return "修改失败！";
    }

}
